<!--
 * @Author      : 徐博
 * @Date        : 2024-05-21 17:48:55
 * @LastEditTime: 2024-05-21 17:50:47
 * @LastEditors : 徐博
 * @FilePath    : /Users/xubo/study/vue3/vue3-ts-vite/src/components/fe-menu/fe-menu.vue
 * @Description : desc
 */
 -->

<template>
  <div>
    <a-menu v-model:selectedKeys="state.selectedKeys" mode="inline" :open-keys="state.openKeys"
      @openChange="onOpenChange">
      <template v-for="item in props.menus" :key="item.id" >
        <fe-menu-item v-if="item?.children" :menu-item="item" @openChange="onOpenChange"></fe-menu-item>
        <a-menu-item v-else :key="item.id" @click.native="goTo(item)">
          <template #icon>
            <component class="icon-font" :is="proxy.$icons[item.icon]"></component>
          </template>
          {{ t(item.name)  }}
        </a-menu-item>
      </template>
    </a-menu>
  </div>
</template>

<script setup lang="ts">
import { reactive, defineProps } from 'vue';
import FeMenuItem from './fe-menu-item.vue';
import {useI18n} from "vue-i18n";
import { useRouter } from 'vue-router';
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()
const {t} = useI18n();

const router = useRouter()

const props = defineProps(['menus'])

const state = reactive({
  rootSubmenuKeys: props.menus.map((item: { id: number| string }) => item.id),
  openKeys: ['0'],
  selectedKeys: [],
});
const onOpenChange = (openKeys: string[]) => {
  const latestOpenKey = openKeys.find(key => state.openKeys.indexOf(key) === -1);
  if (state.rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
    state.openKeys = openKeys;
  } else {
    state.openKeys = latestOpenKey ? [latestOpenKey] : [];
  }
}

const goTo = (item: any) => {
  if(item.iframe) {
    router.push({
      path: '/iframe',
      query: {
        src: item.iframe
      }
    })
  }else {
    router.push(item.url)
  }
}

</script>

<style lang="less" scoped>
.icon-font {
  font-size: 24px;
}
</style>
